//
// Created by kqbi on 2020/2/24.
//

#include "HttpServer.h"
#include "OXFWorkPoller.h"
#include "Common/Config.h"
#include "json/json.h"
#include "Utils/Logger.h"
//#include "model.h"

HttpServer::HttpServer(std::weak_ptr<HttpService> httpService):_httpService(httpService) {
    _httpServer = S_HttpServer_Create(OXFWorkPollerPool::Instance()._ioc);
}

HttpServer::~HttpServer() {

}

bool HttpServer::Listen() {
    return S_HttpServer_Listen(_httpServer, std::string(""),
                               Config::getInstance()->_httpServerInfo.getPort());
}

void HttpServer::AddFilePath(const std::string &filePath) {
   // S_HttpServer_AddFilePath(filePath);
}

void HttpServer::InitHandle() {
    auto result =
            [&](std::string connectionId, VIICS_status status, std::string result) {
        Json::Value root;
        Json::Reader reader;
        Json::StyledWriter writer;
        if (!result.empty()) {
            if (!reader.parse(result, root)){
                S_LOG_ERROR("reader parse error");
            }
        }
        root["errorCode"] = status;
        root["errorCodeStr"] = getIPOSSStatusStr(status);
        std::string body = writer.write(root);
        S_HttpServer_SendResMsg(_httpServer, connectionId, 200, body);
    };

    S_HttpServer_AddHandle(_httpServer, "/vehicleService/search", [&](S_HttpReq_Msg *msg) {
        VehicleService_Search vSearch;
        try {
            Json::Value root;
            Json::Reader reader;
            if (reader.parse(msg->_body, root)) {
                S_LOG_DEBUG(msg->_body);
                vSearch.page = root["page"].asInt();
                vSearch.pageSize = root["pageSize"].asInt();
                vSearch._condition.channelId = root["condition"]["channelId"].asString();
                vSearch._condition.beginTime = root["condition"]["beginTime"].asString();
                vSearch._condition.endTime = root["condition"]["endTime"].asString();
                vSearch._condition.queryType = root["condition"]["queryType"].asString();
            }
        } catch(std::exception &e) {
            S_LOG_ERROR(e.what());
            result(msg->_connectionId, VIICS_STATUS_PARAM_ERROR, "");
            return;
        }
        //S_HttpServer_SendResMsg(msg->_connectionId, 200, msg->_header.version, body);
        auto strongSelf = _httpService.lock();
        if (strongSelf)
            strongSelf->VehicleServiceSearch(msg->_connectionId, vSearch, result);
    });
}

void HttpServer::Stop() {
    S_HttpServer_Release(_httpServer);
}